package com.xzc.shopping.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzc.shopping.common.ErrorCode;
import com.xzc.shopping.exception.BusinessException;
import com.xzc.shopping.mapper.ProductMapper;
import com.xzc.shopping.model.vo.ProductVO;
import com.xzc.shopping.model.domain.Product;
import com.xzc.shopping.service.ProductService;
import com.xzc.shopping.service.ThumbService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
* @author Administrator
* @description 针对表【product】的数据库操作Service实现
* @createDate 2025-02-26 08:32:55
*/
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product>
implements ProductService {
    @Resource ProductMapper productMapper;

     private  final ThumbService thumbService;

    @Autowired
    public ProductServiceImpl(@Lazy ThumbService thumbService) { // 延迟加载
        this.thumbService = thumbService;
    }
    /**
     * 增加商品点赞数（原子操作）
     */
    @Override
    public boolean incrementThumbCount(Integer productId) {
        return productMapper.incrementThumbCount(productId) >= 0;
    }


    @Override
    public boolean decrementThumbCount(Integer productId) {
        return productMapper.decrementThumbCount(productId) >= 0;
    }

    @Override
    public ProductVO getProductDetail(Integer productId, Integer userId) {
        // 查询商品基础信息
        Product product = productMapper.selectById(productId);
        if (product == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "商品不存在");
        }

        // 构建 VO 对象
        ProductVO productVO = new ProductVO();
        BeanUtils.copyProperties(product, productVO); // 复制基础字段

        // 设置点赞数
        productVO.setThumbCount(product.getThumbCount());

        // 设置用户是否已点赞
        if (userId != null) {
            productVO.setIsThumbed(thumbService.existsByUserIdAndProductId(userId, productId));
        } else {
            productVO.setIsThumbed(false); // 未登录默认未点赞
        }

        return productVO;
    }

    @Override
    public int getThumbCount(Integer productId) {
        return productMapper.selectById(productId).getThumbCount();
    }

    @Override
    public List<Product> getHotProductsFromDB() {
        // 使用MyBatis-Plus的QueryWrapper构建查询
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("thumb_count") // 按点赞数降序
                .last("LIMIT 10");          // 限制10条记录

        return baseMapper.selectList(queryWrapper);
    }

}
